package com.powernode.common.config;

import com.powernode.common.handle.AppFailureHandler;
import com.powernode.common.handle.AppLoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Autowired
    private AppLoginSuccessHandler appLoginSuccessHandler;

    @Autowired
    private AppFailureHandler appFailureHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                //对于表单的处理
                .formLogin((formLogin) ->{
                    formLogin
                            .usernameParameter("loginAct")
                            .passwordParameter("loginPwd")
                            .loginPage("/api/toLogin") //处理登录界面
                            .loginProcessingUrl("/api/doLogin") //处理登录请求
                            .successHandler(appLoginSuccessHandler)
                            .failureHandler(appFailureHandler);
                        }
                )
                //异常处理器
                .exceptionHandling((exceptionHandling) ->{
                    exceptionHandling
                            .accessDeniedHandler(null);
                })
                .authorizeHttpRequests((authorizeHttpRequests) ->{
                    authorizeHttpRequests
                            .anyRequest().authenticated(); //所有请求都需要认证
                })
                //关闭csrf
                .csrf((csrf)->{
                    csrf.disable();
                })
                //关闭session请求策略
                .sessionManagement((sessionManagement) ->{
                    sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                })
                //推出成功处理器
                .logout((logout) ->{
                    logout.logoutSuccessHandler(null);
                })
                .build();
    }
    //密码加密器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
